package com.jielin.handling.service.auditresult.impl;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.amazonaws.services.s3.model.ObjectMetadata;
import com.github.pagehelper.PageHelper;
import com.jielin.handling.entity.auditrecorder.AuditRecoder;
import com.jielin.handling.entity.auditresult.AuditResult;
import com.jielin.handling.entity.material.MaterialFile;
import com.jielin.handling.entity.material.MaterialType;
import com.jielin.handling.entity.material.MaterialTypeDocument;
import com.jielin.handling.entity.police.Cases;
import com.jielin.handling.entity.tsuspect.TSuspec;
import com.jielin.handling.entity.vo.AuditResultVo;
import com.jielin.handling.entity.vo.CaseAndSuspectVo;
import com.jielin.handling.entity.vo.CaseAuditVo;
import com.jielin.handling.exception.ResultEnum;
import com.jielin.handling.mapper.auditrecorder.AuditRecoderMapper;
import com.jielin.handling.mapper.auditresult.AuditResultMapper;
import com.jielin.handling.mapper.material.MaterialFileMapper;
import com.jielin.handling.mapper.material.MaterialTypeDocumentMapper;
import com.jielin.handling.mapper.material.MaterialTypeMapper;
import com.jielin.handling.mapper.police.PoliceCaseMapper;
import com.jielin.handling.service.auditresult.AuditFailedService;
import com.jielin.handling.service.xsky.XskyService;
import com.jielin.handling.util.ConstantUtil;
import com.jielin.handling.util.DateUtil;
import com.jielin.handling.util.FileUtil;
import com.jielin.handling.util.StringUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import java.io.File;
import java.io.IOException;
import java.math.BigDecimal;
import java.util.*;
import java.util.stream.Collectors;

/**
 * Created by wangjienice on 2019-04-01.
 */
@Service
@Slf4j
public class AuditFailedServiceImpl implements AuditFailedService {
    @Autowired
    private AuditResultMapper auditresultMapper;
    @Autowired
    private PoliceCaseMapper policeCaseMapper;
    @Autowired
    private AuditRecoderMapper auditRecoderMapper;
    @Autowired
    private MaterialTypeMapper mtMapper;
    @Autowired
    private MaterialTypeDocumentMapper mTypeDocumentMapper;
    @Autowired
    private MaterialFileMapper mfMapper;
    @Autowired
    private XskyService xskyService;

    @Override
    public List<AuditResult> auditFailed(AuditResult auditresult) {
        log.info("auditresult:{}", JSONObject.toJSONString(auditresult));
        List<AuditResult> list = null;
        try {
            PageHelper.startPage(auditresult.getPageNum(), auditresult.getPageSize());
            list = auditresultMapper.auditFailed(auditresult);
        } catch (Exception e) {
            log.error("查询异常={}", e);
        }
        return list;
    }

    @Override
    public List<AuditResult> throughAuditing(AuditResult auditresult) {
        log.info("auditresult:{}", JSONObject.toJSONString(auditresult));
        List<AuditResult> list = null;
        try {
            PageHelper.startPage(auditresult.getPageNum(), auditresult.getPageSize());
            list = auditresultMapper.throughAuditing(auditresult);
        } catch (Exception e) {
            log.error("查询异常={}", e);
        }
        return list;
    }

    @Override
    public List<Cases> waitCheck(Cases casess) {
        log.info("casess:{}", JSONObject.toJSONString(casess));
        List<Cases> list = null;
        try {
            PageHelper.startPage(casess.getPageNum(), casess.getPageSize());
            list = policeCaseMapper.waitCheck(casess);
        } catch (Exception e) {
            log.error("查询异常={}", e);
        }
        return list;
    }

    @Override
    public List<Cases> dossierInformation(Cases cases) {
        log.info("Cases:{}", JSONObject.toJSONString(cases));
        List<Cases> list = null;
        try {
            PageHelper.startPage(cases.getPageNum(), cases.getPageSize());
            list = policeCaseMapper.dossierInformation(cases);
        } catch (Exception e) {
            log.error("查询异常={}", e);
        }
        return list;
    }

    @Override
    @Transactional(propagation = Propagation.REQUIRED, rollbackFor = Exception.class)
    public Integer updateMaterial(AuditResult auditResult) {
        log.info("auditResult:{}", JSONObject.toJSONString(auditResult));
        try {
            int value = policeCaseMapper.updateMaterial(auditResult);// 卷宗状态的改变
            if (auditResult.getMaterialStatus().equals("2")) {
                String caseCode = policeCaseMapper.selectCaseCodeByAuditId(auditResult.getId());// 通过卷宗id拿到案件编号(二次审讯)
                int auditNumber = policeCaseMapper.selectAuditNumber(caseCode);// 通过案件编号查询该案件下最新审讯的卷宗数
                int auditPassNumber = policeCaseMapper.selectAuditPassNumber(caseCode);// 最新卷宗审核通过数量
                Map map = new HashMap();
                map.put("auditNumber", auditNumber);
                map.put("auditPassNumber", auditPassNumber);
                map.put("caseCode", caseCode);
                if(auditNumber!=0 || auditPassNumber!=0){
                    policeCaseMapper.updateNumber(map);// 根据单位编号更新案件表里面的卷宗个数和卷宗通过个数
                    if (auditNumber == auditPassNumber ) {// 卷宗个数和卷宗通过个数相等则更新该案件为已完结案件
                        policeCaseMapper.updateCaseStaus(caseCode);
                    }
                }
            }
            auditResult.setAuditorId(StringUtil.generatorUUID());
            auditresultMapper.insertAuditRecorde(auditResult);// 新增卷宗记录
            return value;
        } catch (Exception e) {
            log.info("service 事务回滚:{}", e);
            // 抛出异常让其回滚
            throw new RuntimeException("事务回滚");
        }
    }

    @Override
    public int insertAuditRecorde(AuditResult auditResult) {

        return auditresultMapper.insertAuditRecorde(auditResult);
    }

    @Override
    public List<AuditResult> selectSuectByAccessLibrary(String name, String caseCode) {
        Map map = new HashMap();
        map.put("name", name);
        map.put("caseCode", caseCode);
        return auditresultMapper.selectSuectByAccessLibrary(map);
    }

    @Override
    public List<AuditResult> selectCasecodeInCabin(String handleUnitCode, String drawerCode) {
        List<AuditResult> list = auditresultMapper.selectCasecodeInCabin(handleUnitCode, drawerCode);
        return list;
    }

    @Override
    public Map selectStateInCabin(String handleUnitCode) {
        List<CaseAndSuspectVo> list1 = auditresultMapper.selectStateInCabin(handleUnitCode);//查询主柜集合
        List<CaseAndSuspectVo> list2 = auditresultMapper.selectStateInViceCabin(handleUnitCode);//查询副柜子集合
        Map<String, List<CaseAndSuspectVo>> resultList = list2.stream().collect(Collectors.groupingBy(CaseAndSuspectVo::getCabinetId));

        Map map = new HashMap();
        map.put("main", list1);
        map.put("Vice", resultList);
        return map;
    }

    @Override
    public CaseAndSuspectVo selectCountInCabin(String handleUnitCode) {
        return auditresultMapper.selectCountInCabin(handleUnitCode);
    }

    @Override
    public List<CaseAndSuspectVo> selectCabinetNumber(String id) {
        return auditresultMapper.selectCabinetNumber(id);
    }

    @Override
    public List<TSuspec> waitCheckSuspectList(String unicode,String caseCode,String materialStatus) {
        return auditresultMapper.waitCheckSuspectList(unicode,caseCode, materialStatus);
    }

    @Override
    public List<Cases> completeCase(Cases casess) {
        log.info("casess:{}", casess);
        List<Cases> list = null;
        try {
            PageHelper.startPage(casess.getPageNum(), casess.getPageSize());
            list = policeCaseMapper.completeCase(casess);
            for (Cases cases : list) {
                if (!StringUtil.isEmpty(cases.getCrimetime())) {
                    String number = cases.getCrimetime();
                    String startDate = number.substring(0, number.indexOf("-"));
                    String endDate = number.substring(number.indexOf("-") + 1);
                    Date dd = DateUtil.getDateByBaseStr(startDate, DateUtil.LOCATE_DATE_FORMAT);
                    String editStartDate = DateUtil.formatDate(dd, DateUtil.DATE_FORMAT_MINUS);

                    Date dd1 = DateUtil.getDateByBaseStr(endDate, DateUtil.LOCATE_DATE_FORMAT);
                    String editEndDate = DateUtil.formatDate(dd1, DateUtil.DATE_FORMAT_MINUS);
                    // String editEndDate=DateUtil.stampToDate(endDate);
                    cases.setCrimetime(editStartDate + "——" + editEndDate);
                }
            }
        } catch (Exception e) {
            log.error("查询异常={}", e);
        }
        return list;
    }

    @Override
    public CaseAuditVo selectAccessLibrary(String unicode) {
        log.info("unicode:{}", unicode);
        return policeCaseMapper.selectAccessLibrary(unicode);
    }

    @Override
    public List<AuditResult> selectAccessList(AuditResult auditResult) {
        log.info("auditResult:{}", auditResult);
        List<AuditResult> list = null;
        try {
            PageHelper.startPage(auditResult.getPageNum(), auditResult.getPageSize());
            list = auditresultMapper.selectAccessList(auditResult);
//			if(list.size()>0){
//				for  ( int  i  =   0 ; i  <  list.size()  -   1 ; i ++ ) {
//					for (int j = list.size() - 1; j > i; j--) {
//						if (list.get(j).getDrawerCode().equals(list.get(i).getDrawerCode())) {
//							list.remove(j);
//						}
//					}
//				}
//				//插入获取到的此单位的案件信息
//			}
            for (AuditResult auditResult1 : list) {
                if (auditResult1 != null) {
                    //去除字符串最后一位","
                    if (auditResult1.getDrawerCode().endsWith(",")) {
                        auditResult1.setDrawerCode(auditResult1.getDrawerCode().substring(0, auditResult1.getDrawerCode().length() - 1));
                    }
                    //去掉字符串首位","
                    if (auditResult1.getDrawerCode().startsWith(",")) {
                        auditResult1.setDrawerCode(auditResult1.getDrawerCode().substring(1, auditResult1.getDrawerCode().length()));
                    }
                }
            }
        } catch (Exception e) {
            log.error("查询异常={}", e);
        }
        return list;
    }

    @Override
    public List<AuditRecoder> selectInAndOutAuditById(String id, int pageSize, int pageNum) {
        log.info("id:{}", JSONObject.toJSONString(id));
        List<AuditRecoder> list = null;
        try {
            PageHelper.startPage(pageSize, pageNum);
            list = auditRecoderMapper.selectInAndOutAuditById(id);
            for (AuditRecoder auditRecoder : list) {

            }
        } catch (Exception e) {
            log.error("查询异常={}", e);
        }
        return list;
    }

    @Override
    @Transactional(propagation = Propagation.REQUIRED, rollbackFor = Exception.class)
    public int entryLibrary(HashMap<String, String> map) {
        log.info("map:{}", JSONObject.toJSONString(map));
        int i = 0;
        try {
            String id = auditRecoderMapper.selectUnitCode(map.get("caseCode"));//根据案件编号查询单位id
            auditRecoderMapper.updateByIdValue(map.get("idValue"));//通过身份证号修改是否为最新的记录
            i = auditRecoderMapper.entryLibrary(map);//卷宗入库记录的新增
            auditRecoderMapper.updateCabinetState(map.get("drawerCode"), id);//通过单位编号和柜号减少该柜子中卷宗的数目
            auditRecoderMapper.updateState(map.get("idValue"), map.get("caseCode"));//以卷宗为单位的卷轴你那个状态改变
        } catch (Exception e) {
            log.info("service 事务回滚:{}", e);
            // 抛出异常让其回滚
            throw new RuntimeException("事务回滚");
        }
        return i;
    }

    @Override
    @Transactional(propagation = Propagation.REQUIRED, rollbackFor = Exception.class)
    public int borrowDossier(HashMap<String, String> map) {
        log.info("map:{}", JSONObject.toJSONString(map));
        int i = 0;
        try {
            String id = auditRecoderMapper.selectUnitCode(map.get("caseCode"));//根据案件编号查询单位id
            auditRecoderMapper.updateByIdValue(map.get("idValue"));//通过身份证号修改是否为最新的记录
            auditRecoderMapper.deleteState(map.get("drawerCode"), id);//通过单位编号和柜号减少该柜子中卷宗的数目
            i = auditRecoderMapper.borrowDossier(map);//卷宗入库记录的新增
            auditRecoderMapper.updateOutState(map.get("idValue"), map.get("caseCode"));//卷宗借阅或移交改变为不在库的状态
        } catch (Exception e) {
            log.info("service 事务回滚:{}", e);
            // 抛出异常让其回滚
            throw new RuntimeException("事务回滚");
        }
        return i;
    }

    @Override
    public String selectRecoderId(String caseCode) {
        return auditRecoderMapper.selectRecoderId(caseCode);
    }

    @Override
    @Transactional(propagation = Propagation.REQUIRED, rollbackFor = Exception.class)
    public int returnDossier(HashMap<String, String> map) {
        int i = 0;
        try {
            String id = auditRecoderMapper.selectUnitCode(map.get("caseCode"));//根据案件编号查询单位id
            auditRecoderMapper.updateByIdValue(map.get("idValue"));//通过身份证号修改是否为最新的记录
            i = auditRecoderMapper.returnDossier(map);//借阅归还
            auditRecoderMapper.updateCabinetState(map.get("drawerCode"), id);//通过单位编号和柜号增加该柜子中卷宗的数目
            auditRecoderMapper.updateState(map.get("idValue"), map.get("caseCode"));//以人为单位的卷宗入库时以卷宗为单位的卷宗状态的改变
        } catch (Exception e) {
            log.info("service 事务回滚:{}", e);
            // 抛出异常让其回滚
            throw new RuntimeException("事务回滚");
        }
        return i;
    }

    @Override
    @Transactional(propagation = Propagation.REQUIRED, rollbackFor = Exception.class)
    public int transferDossier(JSONObject jsonObject) {
        JSONArray array = jsonObject.getJSONArray("listArray");// 取出前台传卷宗id和柜号等等
        JSONObject json = null;
        int J = 0;
        int M = 0;
        try {
            AuditRecoder auditRecoder = jsonObject.getObject("AuditRecoder", AuditRecoder.class);// 前台传的对象
            auditRecoder.setId(StringUtil.generatorUUID());
            if (array != null && array.size() > 0) {
                for (int i = 0; i < array.size(); i++) {
                    HashMap<String, String> map = new HashMap();
                    json = (JSONObject) array.get(i);
                    map.put("id", StringUtil.generatorUUID());
                    map.put("name", json.get("name").toString());
                    map.put("idValue", json.get("idValue").toString());
                    map.put("transferDate", DateUtil.formatDate(json.getDate("transferDate"), DateUtil.DATE_FORMAT_MINUS));
                    map.put("transferName", json.get("transferName").toString());
                    map.put("transferCode", json.get("transferCode").toString());
                    if (!StringUtil.isEmpty(json.get("transfeReason").toString())) {
                        map.put("transfeReason", (String) json.get("transfeReason").toString());
                    }
                    if (!StringUtil.isEmpty(json.get("transferCauseAndType").toString())) {
                        map.put("transferCauseAndType", (String) json.get("transferCauseAndType"));
                    }
                    map.put("caseCode", auditRecoder.getCaseCode());
                    map.put("caseName", auditRecoder.getCaseName());
                    map.put("transferPoliceName", auditRecoder.getTransferPoliceName());
                    map.put("transferPoliceCode", auditRecoder.getTransferPoliceCode());
                    map.put("accessLibrary", "4");
                    auditRecoderMapper.updateByIdValue(map.get("idValue"));
//				AuditResult auditResult = new AuditResult();
//				auditResult.setAccessLibrary("4");
//				auditResult.setId(map.get("auditId").toString());
                    J = auditRecoderMapper.transferDossier(map);
                    String id = auditRecoderMapper.selectUnitCode(map.get("caseCode"));
                    auditRecoderMapper.updateCabinetState(map.get("drawerCode"), id);
                    auditRecoderMapper.updateOutState(map.get("idValue"), map.get("caseCode"));//卷宗借阅或移交改变为不在库的状态
                    M += J;
                }
            }
        } catch (Exception e) {
            log.info("service 事务回滚:{}", e);
            // 抛出异常让其回滚
            throw new RuntimeException("事务回滚");
        }
        return M;
    }

    @Override
    public List<AuditRecoder> transferList(AuditRecoder auditRecoder) {
        log.info("auditRecoder:{}", auditRecoder);
        List<AuditRecoder> list = null;
        try {
            PageHelper.startPage(auditRecoder.getPageNum(), auditRecoder.getPageSize());
            list = auditRecoderMapper.transferList(auditRecoder);
        } catch (Exception e) {
            log.error("查询异常={}", e);
        }
        return list;
    }

    @Override
    public int insertAudit(AuditResult auditResult) {
        log.info("auditResult:{}", auditResult);
        String id = StringUtil.generatorUUID();
        auditResult.setId(id);
        return auditRecoderMapper.insertAudit(auditResult);
    }

    @Transactional(propagation = Propagation.REQUIRED, rollbackFor = Exception.class)
    @Override
    public int updataWithdraw(String id, String caseCode, String policeId, String caseSuspectId) {
        if (StringUtil.isEmpty(id) || StringUtil.isEmpty(caseCode) || StringUtil.isEmpty(policeId)
                || StringUtil.isEmpty(caseSuspectId)) {
            log.info("参数为空");
            return -1;
        }
        // 查询要撤回的卷宗数据
        List<MaterialType> mtList = mtMapper.findMaterialByCaseCode(caseCode, caseSuspectId, policeId, 0);
        if (mtList == null || mtList.size() == 0) {
            log.info("没有查询到卷宗信息");
            return -1;
        }
        int i = -1;
        List<String> mtIds = null;// 原来的卷宗1级id
        List<String> copyMtIds = null;// 复制后的卷宗1级id

        log.info("id:{}", id);
        Map map = new HashMap();
        map.put("caseCode", caseCode);
        map.put("policeId", policeId);
        map.put("caseSuspectId", caseSuspectId);
        int count = auditresultMapper.selectAuditCount(map);// 统计该类型卷宗数量

        try {
            // 卷宗撤回留痕处理
            // 1.复制原本的卷宗材料
            mtIds = new ArrayList<String>();
            copyMtIds = new ArrayList<String>();
            for (int z = 0; z < mtList.size(); z++) {
                mtIds.add(mtList.get(z).getId());
                mtList.get(z).setId(StringUtil.generatorUUID());
                mtList.get(z).setIsRetract(count);
                copyMtIds.add(mtList.get(z).getId());
            }
            mtMapper.addMaterialTypes(mtList);// 复制以前的数据

            for (int j = 0; j < mtList.size(); j++) {
                List<MaterialTypeDocument> mtdList = mTypeDocumentMapper.findDocumentByMaterialTypeIds(mtIds.get(j));
                if (mtdList == null || mtdList.size() == 0) {
                    log.info("没有查询到文件夹信息");
                } else {
                    for (int k = 0; k < mtdList.size(); k++) {
                        String beforeDocId = mtdList.get(k).getId();
                        mtdList.get(k).setId(StringUtil.generatorUUID());
                        String thisMaterialTypeId = mtList.get(j).getId();
                        mtdList.get(k).setMaterialtypeid(thisMaterialTypeId);

                        List<MaterialFile> mfList = mfMapper.findFileByDocumentId(beforeDocId, "");
                        if (mfList == null || mfList.size() == 0) {
                            log.info("没有查询到文件信息");
                        } else {
                            for (MaterialFile mf : mfList) {
                                mf.setId(StringUtil.generatorUUID());
                                mf.setMaterialtypedocumentid(mtdList.get(k).getId());
                                try {
                                    File file = null;
                                    // 复制源文件
                                    if (!StringUtil.isEmpty(mf.getUrl())) {
                                        String filePath = mf.getUrl();
                                        String modifyfilePath = filePath.substring(filePath.lastIndexOf("."),
                                                filePath.length());
                                        String endFilePath = filePath.replace(modifyfilePath,
                                                "retract" + count + modifyfilePath);
                                        if (ConstantUtil.XSKYRESTORAGE) {
                                            try {
                                                xskyService.copyObject(ConstantUtil.XSKY_BUCKET_DOSSIER, filePath.substring(ConstantUtil.XSKY_PREPATH_URL.length())
                                                        , ConstantUtil.XSKY_BUCKET_DOSSIER, endFilePath, new ObjectMetadata());
                                                mf.setUrl(endFilePath);
                                            } catch (Exception e) {
                                                throw new RuntimeException(ResultEnum.XSKYCOPYFAIL.getMsg(), e);
                                            }
                                        } else {
                                            file = new File(filePath);
                                            if (file.exists() && file.isFile()) {
                                                FileUtil.copyFile(new File(filePath), new File(endFilePath));
                                                mf.setUrl(endFilePath);
                                            }
                                        }
                                    }
                                    // 复制缩略图
                                    if (!StringUtil.isEmpty(mf.getThumbnailpath())) {
                                        String thumbnailPath = mf.getThumbnailpath();
                                        String modifyThumbnailPath = thumbnailPath
                                                .substring(thumbnailPath.lastIndexOf("."), thumbnailPath.length());
                                        String endThumbnailPath = thumbnailPath.replace(modifyThumbnailPath,
                                                "retract" + count + modifyThumbnailPath);
                                        if (ConstantUtil.XSKYRESTORAGE) {
                                            try {
                                                xskyService.copyObject(ConstantUtil.XSKY_BUCKET_DOSSIER, thumbnailPath.substring(ConstantUtil.XSKY_PREPATH_URL.length())
                                                        , ConstantUtil.XSKY_BUCKET_DOSSIER, endThumbnailPath, new ObjectMetadata());
                                                mf.setThumbnailpath(endThumbnailPath);
                                            } catch (Exception e) {
                                                throw new RuntimeException(ResultEnum.XSKYCOPYFAIL.getMsg(), e);
                                            }
                                        } else {
                                            file = new File(thumbnailPath);
                                            if (file.exists() && file.isFile()) {
                                                FileUtil.copyFile(new File(thumbnailPath), new File(endThumbnailPath));
                                                mf.setThumbnailpath(endThumbnailPath);
                                            }
                                        }
                                    }
                                } catch (IOException e) {
                                    log.error("复制文件出错：" + e);
                                    throw new RuntimeException("复制文件出错", e);
                                }
                            }
                            mfMapper.addFiles(mfList);
                        }
                    }
                    mTypeDocumentMapper.addDocuments(mtdList);// 复制文件夹信息
                }
            }

            // 2.修改原本的卷宗材料为已撤回
            // edit wr ：新增时已经修改
//            mtMapper.updateIsRetract(copyMtIds, count);

            auditresultMapper.updataWithdraw(id);// 根据id改变卷宗是否撤回状态为1
            AuditResult audit = auditresultMapper.selectByPrimaryKey(id);// 根据id查询卷宗信息
            if (audit != null) {
                audit.setId(StringUtil.generatorUUID());
                audit.setWithdrawalsCount(count);
                audit.setMaterialStatus("0");
                audit.setWhetherToWithdraw(0);
                auditresultMapper.insert(audit);
                // auditresultMapper.updataWithdraw(audit.getId());//新增卷宗状态为待上传的是否撤回改为1
            }
            i = 1;
        } catch (Exception e) {
            log.info("AuditFailedService 事务回滚:{}", e);
            // 抛出异常让其回滚
            throw new RuntimeException("事务回滚");
        }

        return i;
    }

    @Override
    public String selectMaterialPassRate(String unitCode) {
        return auditresultMapper.selectMaterialPassRate(unitCode);
    }

    @Override
    public List<AuditResultVo> selectMaterialGroupByPolice(String unitCode, String policeCode, String policeName) {
        if (StringUtil.isEmpty(unitCode)) {
            return null;
        }
        List<AuditResultVo> arvlist = auditresultMapper.selectMaterialGroupByPolice(unitCode, policeCode, policeName);
        if (arvlist.size() > 0) {
            for (AuditResultVo arv : arvlist) {
                AuditResultVo vo = auditresultMapper.selectMaterialByPoliceId(arv.getPoliceId());
                arv.setPassNum(vo.getPassNum());
                arv.setNoPassNum(vo.getNoPassNum());
                int rate = (int) ((new BigDecimal((float) vo.getPassNum() / arv.getMaterialCount())
                        .setScale(2, BigDecimal.ROUND_HALF_UP).doubleValue()) * 100);
                arv.setPassRate(rate + "%");
            }
        }
        return arvlist;
    }

    @Override
    public List<AuditResult> selectMaterialByCaseCode(AuditResult auditResult) {
        log.info("auditRecoder:{}", JSONObject.toJSONString(auditResult));
        List<AuditResult> list = auditresultMapper.selectMaterialByCaseCode(auditResult);
        return list;
    }

    @Override
    public List<AuditResult> selectMaterialByAccessLibrary(AuditResult auditResult) {
        return auditresultMapper.selectMaterialByAccessLibrary(auditResult);
    }

    @Override
    public List<AuditResult> selectDosserList(String caseCode, String materialStatus, String policeId,
                                              String handleUnitCode) {
        Map map = new HashMap();
        map.put("caseCode", caseCode);
        map.put("materialStatus", materialStatus);
        map.put("policeId", policeId);
        map.put("handleUnitCode", handleUnitCode);
        return auditresultMapper.selectDosserList(map);
    }

    @Override
    public List<AuditResult> selectSuspectDosserList(String caseCode, String materialStatus, String policeId) {
        Map map = new HashMap();
        map.put("caseCode", caseCode);
        map.put("materialStatus", materialStatus);
        //map.put("whetherToWithdraw", whetherToWithdraw);
        map.put("policeId", policeId);
        return auditresultMapper.selectSuspectDosserList(map);
    }

    @Override
    public Map selectCaseAndSuspect(String caseCode, String idValue) {
        HashMap map1 = new HashMap();
        HashMap map = new HashMap();
        CaseAndSuspectVo caseAndSuspectVo = auditresultMapper.selectCaseAndSuspect(caseCode, idValue);

        if (caseAndSuspectVo == null) {
            map1.put("caseAndSuspectVo", 0);
        } else {
            map1.put("caseAndSuspectVo", caseAndSuspectVo);
        }
        map.put("caseCode", caseCode);
        map.put("idValue", idValue);
        Cases cases = policeCaseMapper.selectByCaseCode(map);
        map1.put("cases", cases);
        return map1;
    }

    @Override
    public List<AuditRecoder> selectInAndOut(AuditRecoder auditRecoder) {
        List<AuditRecoder> list = auditRecoderMapper.selectInAndOut(auditRecoder);
        for (AuditRecoder auditRecoder1 : list) {
            if (auditRecoder1.getBorrowDate() != null && auditRecoder1.getReturnDate() == null) {
                Calendar cal = Calendar.getInstance();
                cal.setTime(auditRecoder1.getBorrowDate());
                long time1 = cal.getTimeInMillis();
                cal.setTime(new Date());
                long time2 = cal.getTimeInMillis();
                long between_days = (time2 - time1) / (1000 * 3600 * 24);
                int i = Integer.parseInt(String.valueOf(between_days));
                auditRecoder1.setDayTime(String.valueOf(i));
            } else {
                auditRecoder1.setDayTime("0");
            }
        }
        return list;
    }

    @Override
    public List<AuditResult> selectByCaseCode(String caseCode) {

        return auditresultMapper.selectByCaseCode(caseCode);
    }

    @Override
    public List<AuditResult> selectAllAuditByUnitCode(AuditRecoder auditRecoder) {
        List<AuditResult> list = null;
        try {
            PageHelper.startPage(auditRecoder.getPageNum(), auditRecoder.getPageSize());
            list = auditresultMapper.selectAllAuditByUnitCode(auditRecoder);
        } catch (Exception e) {
            log.error("查询异常={}", e);
        }
        return list;
    }

    @Override
    public AuditResult selectById(String id) {
        if (StringUtil.isEmpty(id)) {
            return null;
        }
        return auditresultMapper.selectByPrimaryKey(id);
    }

}
